package com.hdl.school.utils;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.hdl.school.application.MyApplication;
import com.hdl.school.bean.PlanTask;
import com.hdl.school.schoolcontroller.VlcVideoActivity;

import java.io.File;

/**
 * Created by yunjian on 16/10/9.
 */
public class MediaUtils {
   static  String[] video_extensions = {
            ".3g2", ".3gp", ".3gp2", ".3gpp", ".amv", ".asf", ".avi", ".divx", ".drc", ".dv",
            ".f4v", ".flv", ".gvi", ".gxf", ".ismv", ".iso", ".m1v", ".m2v", ".m2t", ".m2ts",
            ".m4v", ".mkv", ".mov", ".mp2", ".mp2v", ".mp4", ".mp4v", ".mpe", ".mpeg",
            ".mpeg1", ".mpeg2", ".mpeg4", ".mpg", ".mpv2", ".mts", ".mtv", ".mxf", ".mxg",
            ".nsv", ".nut", ".nuv", ".ogm", ".ogv", ".ogx", ".ps", ".rec", ".rm", ".rmvb",
            ".tod", ".ts", ".tts", ".vob", ".vro", ".webm", ".wm", ".wmv", ".wtv", ".xesc" };

    static String[] audio_extensions = {
            ".3ga", ".a52", ".aac", ".ac3", ".adt", ".adts", ".aif", ".aifc", ".aiff", ".amr",
            ".aob", ".ape", ".awb", ".caf", ".dts", ".flac", ".it", ".m4a", ".m4b", ".m4p",
            ".mid", ".mka", ".mlp", ".mod", ".mpa", ".mp1", ".mp2", ".mp3", ".mpc", ".mpga",
            ".oga", ".ogg", ".oma", ".opus", ".ra", ".ram", ".rmi", ".s3m", ".spx", ".tta",
            ".voc", ".vqf", ".w64", ".wav", ".wma", ".wv", ".xa", ".xm" };



    public static void playMedia(final Context context, PlanTask planTask) {
        if (TextUtils.isEmpty(planTask.getFileUrl())) {
            Toast.makeText(context, "无法播放空路径", Toast.LENGTH_SHORT).show();
            return;
        }
        String url=planTask.getFileUrl();
        int index = url.lastIndexOf(".");
        if (index > 0 && index < url.length() - 1) {
            String pex = url.substring(index);
            String taskStr=JSON.toJSONString(planTask);
            if (arrayContain(audio_extensions,pex)) {
                Log.e("media", "播放音频"+url);
                Intent intent = new Intent(BroadcastAction.ACTION_MEDIA_ENVENT);
                intent.putExtra("action","play");
                intent.putExtra("media_type",1);
                intent.putExtra("task",taskStr);
                context.sendBroadcast(intent);
                if(planTask.getStopOther()==1&&MyApplication.getAppContext().isMediaPlaying()){
                    Intent stopIntent = new Intent(BroadcastAction.ACTION_MEDIA_ENVENT);
                    stopIntent.putExtra("action","stopVideo");
                    context.sendBroadcast(stopIntent);
                }

            } else if(arrayContain(video_extensions,pex)||url.startsWith("udp")||url.startsWith("rtsp")||url.startsWith("rtmp")){
                Log.e("media", "播放视频"+url);
                if(MyApplication.getAppContext().isMediaPlaying()){
                    //正在播放，延时开始新的播放
                     Handler handler=new Handler(){
                         @Override
                         public void handleMessage(@NonNull Message msg) {
                             super.handleMessage(msg);
                             Intent intent = new Intent(context, VlcVideoActivity.class);
                             intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP);
                             intent.putExtra("task",(String)msg.obj);
                             context.startActivity(intent);
                         }
                     };
                    Message message=new Message();
                    message.obj=taskStr;
                    handler.sendMessageDelayed(message,2000);
                }else{
                    //立即开始播放
                    Intent intent = new Intent(context, VlcVideoActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    intent.putExtra("task",taskStr);
                    context.startActivity(intent);
                }
                if(planTask.getStopOther()==1&&MyApplication.getAppContext().isAudioPlaying()){
                    Intent stopIntent = new Intent(BroadcastAction.ACTION_MEDIA_ENVENT);
                    stopIntent.putExtra("action","stopMusic");
                    context.sendBroadcast(stopIntent);
                }


            }else{
                Toast.makeText(context, "不支持该文件格式", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(context, "播放路径不合法", Toast.LENGTH_SHORT).show();
        }

    }





    private static  boolean arrayContain(String[] array,String txt){
        for(int i=0;i<array.length;i++){
            if(array[i].equals(txt)){
                return true;
            }
        }
        return false;
    }


    public static void playMediaCheckLocal(Context context, PlanTask planTask) {
        String path = checkLocal(planTask.getFileUrl());
        if (path != null) {
            planTask.setFileUrl(path);
        }
        playMedia(context, planTask);

    }




    public static void stopMeida(Context context,PlanTask planTask) {
        Intent i = new Intent(BroadcastAction.ACTION_MEDIA_ENVENT);
        i.putExtra("action","stopall");
        i.putExtra("task",JSON.toJSONString(planTask));
        context.sendBroadcast(i);
    }


    private static String checkLocal(String url) {
        if(!url.startsWith("http")){
            return null;
        }
        String temp = url.substring(url.lastIndexOf("/") + 1);
        String path = Config.FTP_DOWNLOADDIR + temp;
        File file = new File(Config.FTP_DOWNLOADDIR + temp);
        if (file.exists() && file.length() >100) {
            return path;
        } else {
            return null;
        }
    }



}
